package com.flx.multi.thread.juc.queue.arrayblockingqueue;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author Fenglixiong
 * @Create 2021/11/17 20:21
 * @Description 基于数组的有界队列，数组不可扩容
 **/
public class ArrayBlockingQueueTest {

    /**
     * 创建容量大小为5的有界队列
     */
    private static BlockingQueue<Ball> blockingQueue = new ArrayBlockingQueue<>(2);


    private final static ExecutorService executorService = Executors.newCachedThreadPool();

    public static void main(String[] args) {

        //提交一个向箱子放球的任务
        executorService.submit(()->{
            int i = 1;
            while (true){
                Ball ball = new Ball("编号："+i,"yellow");
                try {
                    System.out.println("准备往箱子放乒乓球："+ball.getNumber());
                    blockingQueue.put(ball);
                    System.out.println("放完乒乓球："+ball.getNumber()+"，当前箱子有"+blockingQueue.size()+"个球");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                i++;
            }
        });

        executorService.submit(()->{
            while (true){
                Ball ball = blockingQueue.take();
                System.out.println("取出一个球："+ball.getNumber()+"，球框还剩下："+blockingQueue.size()+"球");
                Thread.sleep(2000);
            }
        });


    }


    /**
     * 队列大小
     * @return
     */
    public int queueSize(){
        return blockingQueue.size();
    }

    /**
     * 将球放入队列中
     * @param ball
     * @throws InterruptedException
     */
    public void produce(Ball ball) throws InterruptedException {
        blockingQueue.put(ball);
    }

    /**
     * 将球从队列中拿出
     * @return
     * @throws InterruptedException
     */
    public Ball consume() throws InterruptedException {
        return blockingQueue.take();
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Ball {
        /**
         * 编号
         */
        private String number;
        /**
         * 颜色
         */
        private String color;
    }

}
